package hasthi.manager.gui;

import hasthi.common.BaseContext;
import hasthi.common.HasthiException;
import hasthi.common.Utils;
import hasthi.manager.ManagementLogMessageDocument;
import hasthi.manager.ManagementLogMessageDocument.ManagementLogMessage;
import hasthi.manager.monitering.EventListener;
import hasthi.manager.monitering.MoniteringAgent;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumnModel;

import org.apache.xmlbeans.XmlObject;

public class MoniteringPannel extends JPanel{
    private MoniteringAgent moniteringAgent;
    public MoniteringPannel() throws HasthiException {
        super(new BorderLayout());
        final MessageTableModel tableModel = new MessageTableModel();
        
        final JTable table = new JTable(tableModel);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(10);
        columnModel.getColumn(1).setPreferredWidth(60);
        columnModel.getColumn(2).setPreferredWidth(450);
        table.addMouseListener(new MouseListener() {
            public void mouseReleased(MouseEvent e) {}
            public void mousePressed(MouseEvent e) {}
            public void mouseExited(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}
            public void mouseClicked(MouseEvent e) {
                if(table.getSelectedRow() >= 0 && e.getClickCount() > 1){
                    JTextArea area = new JTextArea((String)tableModel.getValueAt(table.getSelectedRow(), 2),5,10);
                    JOptionPane.showMessageDialog(null, area);
                }
            }
        });
        
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane,BorderLayout.CENTER);
        validate();
        
        BaseContext baseConfigContext = new BaseContext(null);
        moniteringAgent = new MoniteringAgent(baseConfigContext.getMessageBrokerUrl(),baseConfigContext.getManagementTopic());
        moniteringAgent.addTrigger(new EventListener() {
            public void performTriggerAction(XmlObject event, XmlObject[] matchingResults)
                    throws HasthiException {
                //System.out.println("Event recived "+ event);
                if(event instanceof ManagementLogMessageDocument){
                    ManagementLogMessageDocument document = (ManagementLogMessageDocument)event;
                    ManagementLogMessage logMessage = document.getManagementLogMessage();
                    String messageAsStr = logMessage.getMesssage();
                    if(logMessage.getDetail() != null){
                        messageAsStr = messageAsStr + " " +logMessage.getDetail();
                    }
                    tableModel.addMessage(new String[]{logMessage.getType().toUpperCase(),
                            logMessage.getSender().replaceAll("http://", ""),messageAsStr});
                    //TODO We should be able to optimize this
                    //tableModel.fireTableStructureChanged();
                    tableModel.fireTableDataChanged();
                }
            }
            public String getSearchPath() {
                return null;
            }
        });
        moniteringAgent.startMonitering();
    }

    
    
//    private Map<String, HostCanvas> hosts = new HashMap<String, HostCanvas>();
//    public MoniteringPannel(ResourceModel resourceModel){
//        setLayout(new GridLayout(7,1));
//        Collection<ManagedResource> resources = resourceModel.getResources();
//        if(resources != null){
//            for(ManagedResource r:resources){
//                if(hosts.containsKey(r.getHost())){
//                    hosts.get(r.getHost()).addResource(new ResourceCanvas(r));
//                }else{
//                    HostCanvas hostCanvas =  new HostCanvas(r.getHost());
//                    add(hostCanvas);
//                    hosts.put(r.getHost(), hostCanvas);
//                    hostCanvas.addResource(new ResourceCanvas(r));
//                }
//            }
//        }
//    }
    public void removeSubscription() throws HasthiException{
        moniteringAgent.stopMonitoring();
    }
    
    
    public class MessageTableModel extends AbstractTableModel{
        private ArrayList<String[]> messages = new ArrayList<String[]>(100);
        
        public MessageTableModel(){
        }
        
        
        public int getColumnCount() {
            return 3;
        }

        public int getRowCount() {
            return messages.size();
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            return messages.get(rowIndex)[columnIndex];
        }

        public void addMessage(String[] data){
            messages.add(data);
//            if(messages.size() > 40){
//                for(int i = 0;i<10;i++){
//                    messages.remove(i);    
//                }
//            }
        if(messages.size() > 35){
              messages.remove(0);    
          }
        }
        

        @Override
        public String getColumnName(int column) {
            switch(column){
                case 0:
                    return "Type";
                case 1:
                    return "Sender";
                default:
                    return "Message";
            }
        }
    }
    
}
